#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/wait.h>

#define LEFT "["
#define RIGHT "]"
#define MAX 32

int i=0;
char str[MAX];
char* argv[MAX]={NULL};
const char* delim=" ";

//命令行打印
void command_printf()
{
  printf(LEFT"%s"":""%s"" ""#"RIGHT" ",getenv("USER"),getenv("HOME"));
}
//命令行获取
char* command_get(char str[MAX],int size)
{
  char* pc=fgets(str,size,stdin);
  //去除换行符
  str[strlen(str)-1]='\0';

  //测试
  //printf("命令行获取测试:\n");
  //int i=0;
  //while(str[i])
  //{
  //  printf("%c",str[i++]);
  //}
  //printf("\n");
  return pc;
}
//命令行提取
void command_extraction(char str[MAX],const char* delim,char* argv[MAX])
{
  int i=0;
  //printf("命令行提取测试:\n");
  argv[i++]=strtok(str,delim);
  while(argv[i-1])
  {
    //printf("argv[%d]=%s\n",i-1,argv[i-1]);
    argv[i++]=strtok(NULL,delim);
  }
  //printf("\n");
  return;
}

//命令行参数调用与回收
void command_use(char* argv[MAX])
{
  pid_t d = fork();
  if(d==0)
  {
      //进程替换
      if(argv[0]==NULL)
      { 
          return;
      }
      int count =  execvp(argv[0],argv);
      if(count<0)perror("execvp failed");
      //子进程退出
      exit(EXIT_FAILURE);
      }
  else
  {
      //回收子进程
      int count = waitpid(-1,NULL,0);                                                                                       
      if(count<0)
      {
          printf("子进程回收失败\n");
      }
   }
  return;
}


int main()
{
  while(1)
  {   //命令行打印
      command_printf();
      //命令获取
      int size=sizeof(str)-1;
      char* pc=command_get(str,size);
      if(pc==NULL)
      {
        printf("读取失败\n");
      }
      //命令行提取
      command_extraction(str,delim,argv);
      //命令行参数调用
      command_use(argv);
      //重置
  }
  return 0;
}
